// 判断浏览器类型
let userAgent = ''
if (typeof navigator !== 'undefined') {
  userAgent = navigator.userAgent.toLowerCase()
}

export const isAliPay = userAgent.indexOf('alipayclient') >= 0

export function ready(callback) {
  return new Promise(resolve => {
    if (window.AlipayJSBridge) {
      resolve()
      if (callback) callback()
      callback()
    } else {
      document.addEventListener(
        'AlipayJSBridgeReady',
        () => {
          resolve()
          if (callback) callback()
        },
        false
      )
    }
  })
}

export function loadSdk() {
  new Promise((resolve, reject) => {
    const loaded = typeof ap !== 'undefined'
    if (loaded) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.src =
      '//gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.inc.min.js'
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}
